﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using ZhongJia.Lock.Core.Data;
using ZhongJia.Lock.Infrastructure.Data;

namespace ZhongJia.Lock.DataMigration
{
    public class DatabaseInitializer : IDatabaseInitializer
    {
        private LockDbContext _dbContext;
        private IServiceProvider _serviceProvider;

        public DatabaseInitializer(
            LockDbContext dbContext,
            IServiceProvider serviceProvider)
        {
            _dbContext = dbContext;
            _serviceProvider = serviceProvider;
        }
        public async Task Seed(IConfiguration config)
        {
            await _dbContext.Database.EnsureDeletedAsync();
            await _dbContext.Database.EnsureCreatedAsync();
            foreach (var seeder in _serviceProvider.GetServices<ISeeder>())
            {
                await seeder.Seed();
            }
        }
    }

    public interface IDatabaseInitializer
    {
        Task Seed(IConfiguration config);
    }
}
